package com.lucene.demo;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

public class LuceneSearcher {
	private JTextField jtfa;
	private JButton jba;
	private JTextField jtfb;
	private JButton jbb;
	private JButton jbc;
	private static JTextArea jta;
	private JTextField jtfc;
	private JButton jbd;
	private JButton jbe;

	private void createAndShowGUI() {
		// String lf = "com.sun.java.swing,plaf,windows.WindowsLookAndFeel";
		// try{
		// UIManager.setLookAndFeel(lf);
		// }catch(Exception e){
		// JOptionPane.showMessageDialog(null,"无法设定外观感觉！");
		// }
		// java外观
		JFrame.setDefaultLookAndFeelDecorated(true);

		JFrame frame = new JFrame("Lucene searcher joe@163.com");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		final JFileChooser fc = new JFileChooser();
		fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

		Container con = frame.getContentPane();
		con.setLayout(new BorderLayout());

		JPanel jpup = new JPanel();
		jpup.setLayout(new GridLayout(2, 2));
		jtfa = new JTextField(30);
		jtfa.setText("C:/testlucene/index");
		jba = new JButton("选择索引的存放路径");
		jba.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int r = fc.showOpenDialog(null);
				if (r == JFileChooser.APPROVE_OPTION) {
					jtfa.setText(fc.getSelectedFile().getPath());
				}
			}
		});

		jtfb = new JTextField(30);
		JButton jbb = new JButton("搜索");
		jbb.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					String indexPath = jtfa.getText();
					String phrase = jtfb.getText();
					LuceneSearcherTool.search(phrase, indexPath);
				} catch (Exception ce) {
					JOptionPane.showMessageDialog(null, "搜索失败", "提示",
							JOptionPane.ERROR_MESSAGE);
				}
			}
		});

		jpup.add(jtfa);
		jpup.add(jba);
		jpup.add(jtfb);
		jpup.add(jbb);

		jta = new JTextArea(10, 30);
		JScrollPane jsp = new JScrollPane(jta);

		JPanel jpdown = new JPanel();
		jpdown.setLayout(new FlowLayout());
		jtfc = new JTextField(35);
		jbd = new JButton("设定导出路径");
		fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
		jbd.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int r = fc.showOpenDialog(null);
				if (r == JFileChooser.APPROVE_OPTION) {
					jtfc.setText(fc.getSelectedFile().getPath());
				}
			}
		});

		jbe = new JButton("导出搜索结果");
		jbe.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					File f = new File(jtfc.getText());
					FileWriter fw = new FileWriter(f);
					PrintWriter pw = new PrintWriter(fw);
					pw.write(jta.getText());
					pw.flush();
					pw.close();
					JOptionPane.showMessageDialog(null, "写入文件成功！", "提示",
							JOptionPane.INFORMATION_MESSAGE);
				} catch (Exception de) {
					JOptionPane.showMessageDialog(null, "写入文件失败！", "提示",
							JOptionPane.ERROR_MESSAGE);
				}
			}
		});

		jpdown.add(jtfc);
		jpdown.add(jbd);
		jpdown.add(jbe);

		con.add(jpup, BorderLayout.NORTH);
		con.add(jsp, BorderLayout.CENTER);
		con.add(jpdown, BorderLayout.SOUTH);

		frame.setSize(200, 100);
		frame.pack();
		frame.setVisible(true);
	}

	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				new LuceneSearcher().createAndShowGUI();
			}
		});
	}

	static class LuceneSearcherTool {
		public static void search(String phrase, String indexPath)
				throws IOException {
			jta.setText(jta.getText() + "正在搜素关键字：" + phrase + "\n");
			try {
				QueryParser queryParser = new QueryParser(Version.LUCENE_30,
						"content", new StandardAnalyzer(Version.LUCENE_30));

				// 将待检索关键字打包成Query对象
				Query query = queryParser.parse(phrase);
				Date start = new Date();
				IndexSearcher searcher = new IndexSearcher(
						IndexReader.open(FSDirectory.open(new File(indexPath))));
				// 使用索引器检索Query，得到检索结果Hits对象
				TopDocs hits = searcher.search(query, 10);// 有变化的地方
				Date end = new Date();

				StringBuffer sb = new StringBuffer();
				sb.append("搜索完毕用时:" + (end.getTime() - start.getTime())
						+ "毫秒\n");
				if (hits.totalHits == 0) {
					sb.append("没有找到您需要的结果");
				} else {
					for (int i = 0; i < hits.scoreDocs.length; i++) {
						try {
							ScoreDoc scoreDoc = hits.scoreDocs[i];// 有变化的地方
							Document doc = searcher.doc(scoreDoc.doc);// 有变化的地方
							sb.append("这是第" + (i + 1) + "个检索结果，文件路径为:"
									+ doc.get("path") + "\n");
						} catch (Exception ex) {

						}

					}
				}
				jta.setText(jta.getText() + sb.toString());
				searcher.close();
			} catch (Exception ex) {
				ex.printStackTrace();
			}

		}
	}
}
